package com.upc.sealback.controller;

import com.upc.sealback.bean.SealUser;
import com.upc.sealback.config.ResponseResult;
import com.upc.sealback.service.SealUserService;
import com.upc.sealback.utils.MsCode;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Controller
public class LoginController {
    @Autowired
    SealUserService sealUserService;

    /**
     * 获取验证码
     * @param request
     * @param phoneNum 电话号码
     * @return 验证码及验证信息
     */
    @ResponseBody
    @GetMapping("api/getCode")
    public ResponseResult<Object> getCode(HttpServletRequest request, @RequestParam String phoneNum) throws Exception {
        ResponseResult<Object> responseResult = MsCode.sendMs(request,phoneNum);
        return responseResult;
    }

    /**
     * 用户注册
     * @param sealUser 用户注册信息
     * @return 是否注册成功的提示
     */
    @ResponseBody
    @PostMapping("api/register")
    public ResponseResult<Object> Register(@NotNull HttpServletRequest request, @RequestBody @NotNull SealUser sealUser) {
        JSONObject json = (JSONObject)request.getSession().getAttribute("MsCode");
        if(sealUser.getUserId() == null){
            return ResponseResult.getErrorResult("400","databaseError");
        }
        SealUser sealUser1 = sealUserService.getUserByUserId(sealUser.getUserId());
        if(sealUser1 == null){//数据库中没有该用户
            if(json != null){
                //如果验证码获取超过3min，则该验证码失效
                if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 3){
                    return ResponseResult.getSuccessResult("timeOut");
                }
                //如果验证码不对，则返回验证码错误
                if(!json.getString("Code").equals(sealUser.getCheckCode())){
                    return ResponseResult.getSuccessResult("codeError");
                }
                sealUser.setUserAvatar("https://sealzy.oss-cn-qingdao.aliyuncs.com/avatar");
                Date data=new Date();
                sealUser.setUserName(sealUser.getUserId());
                sealUser.setCreateTime(data);
                sealUser.setUserRole(0);
                sealUser.setUserStatus(1);
                int result = sealUserService.addUser(sealUser);
                if(result == 1){
                    return ResponseResult.getSuccessResult("success");
                }else {
                    return ResponseResult.getErrorResult("400","databaseError");
                }
            }else {
                return ResponseResult.getSuccessResult("codeError");
            }
        }
        return ResponseResult.getSuccessResult("exist");
    }

    /**
     * 校验账号
     * @param sealUser 账号信息
     * @return 该账号是否正确的提示
     */
    @ResponseBody
    @PostMapping("api/checkPhone")
    public ResponseResult<Object> checkPhone(@NotNull HttpServletRequest request,@RequestBody SealUser sealUser){
        JSONObject json = (JSONObject)request.getSession().getAttribute("MsCode");
        if(sealUser.getUserId() == null){
            return ResponseResult.getErrorResult("400","databaseError");
        }
        SealUser sealUser1 = sealUserService.getUserByUserId(sealUser.getUserId());
        if(sealUser1 == null){
            return ResponseResult.getSuccessResult("noExist");
        }else {
            if(json != null){
                //如果验证码获取超过3min，则该验证码失效
                if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 3){
                    return ResponseResult.getSuccessResult("timeOut");
                }
                //如果验证码正确，则返回success
                if(json.getString("Code").equals(sealUser.getCheckCode())){
                    return ResponseResult.getSuccessResult("success");
                }
            }
        }
        return ResponseResult.getSuccessResult("codeError");
    }

    /**
     * 更新用户信息
     * @param sealUser 用户信息
     * @return 是否更新成功的提示
     */
    @ResponseBody
    @PutMapping("api/updatePassword")
    public ResponseResult<Object> updatePassword(@RequestBody SealUser sealUser){
        if(sealUser.getUserId() == null){
            return ResponseResult.getErrorResult("400","databaseError");
        }
        SealUser sealUser1 = sealUserService.getUserByUserId(sealUser.getUserId());
        if(sealUser1 != null){
            Date date=new Date();
            int result = sealUserService.updatePassword(sealUser.getUserId(),sealUser.getUserPassword(),date);
            if(result == 1){
                return ResponseResult.getSuccessResult("success");
            }else {
                return ResponseResult.getErrorResult("400","databaseError");
            }
        }
        return ResponseResult.getSuccessResult("noExist");
    }

    /**
     * 用户通过账号密码登录
     * @return 是否登录成功的提示
     */
    @ResponseBody
    @PostMapping("api/login")
    public ResponseResult<Object> loginByUsername(@RequestBody SealUser sealUser)
    {
        if(sealUser.getUserId() == null){
            return ResponseResult.getErrorResult("400","databaseError");
        }
        String password = sealUser.getUserPassword();
        SealUser sealUser1 = sealUserService.getUserByUserId(sealUser.getUserId());
        if(sealUser1 == null){
            return ResponseResult.getSuccessResult("noExist");
        }
        if(Objects.equals(password, sealUser1.getUserPassword())){
            return ResponseResult.getSuccessResult(new Date().getTime());
        }else {
            return ResponseResult.getSuccessResult("error");
        }
    }

    /**
     * 用户通过短信验证码登录
     * @param sealUser 用户信息
     * @return
     */
    @ResponseBody
    @PostMapping("api/loginByPhone")
    public ResponseResult<Object> loginByPhone(@NotNull HttpServletRequest request, @RequestBody SealUser sealUser){
        if(sealUser.getUserId() == null){
            return ResponseResult.getErrorResult("400","databaseError");
        }
        SealUser sealUser1 = sealUserService.getUserByUserId(sealUser.getUserId());
        JSONObject json = (JSONObject)request.getSession().getAttribute("MsCode");
        if(sealUser1 != null){
            if(json != null){
                //如果验证码获取超过3min，则该验证码失效
                if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 3){
                    return ResponseResult.getSuccessResult("timeOut");
                }
                //如果验证码正确，则返回success
                if(json.getString("Code").equals(sealUser.getCheckCode())){
                    return ResponseResult.getSuccessResult("success");
                }
            }else {
                return ResponseResult.getSuccessResult("codeError");
            }
        }
        return ResponseResult.getSuccessResult("noExist");
    }

    /**
     * 获取用户信息
     * @param userId 用户id
     * @return 用户信息
     */
    @ResponseBody
    @GetMapping("api/getUserInfo")
    public ResponseResult<Object> getUserInfo(@NotNull @RequestParam String userId){
        SealUser sealUser = sealUserService.getUserByUserId(userId);
        if(sealUser == null){
            return ResponseResult.getErrorResult("404","no");
        }
        return ResponseResult.getSuccessResult(sealUser);
    }
    
    
    /**
     * 退出系统，刷新token
     * @return 当前时间
     */
    @ResponseBody
    @GetMapping("api/logout")
    public Long logOut()
    {
        return new Date().getTime();
    }

    /**
     * 刷新系统，返回token
     * @return 当前时间
     */
    @ResponseBody
    @GetMapping("api/refresh")
    public Long refresh()
    {
        return new Date().getTime();
    }
}
